package cn.lxycx.dataterrace.interceptor.validates;

import java.util.LinkedHashMap;
import java.util.Map;

import cn.lxycx.dataterrace.interceptor.AbsValidateInterceptor;

import javax.servlet.http.HttpServletRequest;

import lxycx.util.validate.Validate.Ret;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.jfinal.core.Controller;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

/**数据更新校验*/
public class UpdateValidate extends AbsValidateInterceptor {
	
	private static Logger log = Logger.getLogger(UpdateValidate.class);

	@Override
	public Ret verify(HttpServletRequest req) {
		String sqlid = req.getParameter("sqlid");
		String rid = req.getParameter("rid");
		Record user = (Record) req.getSession().getAttribute("user");
		if(sqlid!=null&&rid!=null){
			String sql1 = "select s.*,l.limits,l.constraint_select from (select * from data_statement_limit where aid=?) l  left join data_statement s on s.id=l.sid where l.limits like '%UP%' and s.id=? ";
			Record re = Db.findFirst(sql1,user.get("id"),sqlid);		
			//Record re = QueryDao.findByid("data_statement", Integer.parseInt(sqlid),Kv.by("limits like '%UP%'", null));
					//Db.findFirst("select id,sqltext,tablename,wheres,remark from data_statement where id = ?",sqlid);
			String valis = null;

			if(re !=null){
				valis = re.getStr("updates");
				try {
					if(valis!=null){
						JSONObject json = JSONObject.fromObject(valis);
						Map<String,String> where = new LinkedHashMap<String,String>();
						
						
						if(json.containsKey("where")){where = json.getJSONObject("where");}
						
						String constraint_select = re.get("constraint_select");
						if(StringUtils.isNotBlank(constraint_select)){
							try {
								where.putAll(JSONObject.fromObject(constraint_select));
							} catch (Exception e) {
								log.error("无效的constraint_select："+sqlid);
							}
						}
						
						req.setAttribute("where",where);
						req.setAttribute("fail_hint", json.optString("fail_hint",""));
						return InsertValidate.jsonValidate(req, re, json.getJSONObject("field").toString());
						
					}else{
						return new Ret(false, -5, "无法编辑");
					}
				} catch (Exception e) {
					return new Ret(false, -5, "无法编辑");
				}					

			}else{
				return new Ret(false, -3, "权限不足");
			}

		}else{
			return new Ret(false, -4, "无效的表");
		}
		
	}
	
	@Override
	protected void render(Controller con) {
		super.render(con);
	}

}
